/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package com.vii.streamline.rest;

import com.vii.streamline.CommServlet;
import com.vii.streamline.services.error.StreamLineException;
import com.vii.streamline.services.json.JsonServices;
import com.vii.streamline.services.reflection.Invocation;
import com.vii.streamline.web.HttpServices;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * Specialised Servlet class representing a dispatcher providing a RESTful web services interface delegating all incoming calls to the internal business logic.
 */
public abstract class RestDispatcherServlet extends CommServlet {

    protected abstract Object call(Invocation invocation) throws StreamLineException;

    protected String[] getRequestInfo(HttpServletRequest req) throws StreamLineException {
        String uri = req.getRequestURI().substring(req.getContextPath().length() + 1);

        String[] request = uri.split("\\/");

        if (request.length < 2)
            throw new StreamLineException("Invalid method call: " + uri);

        return request;
    }

    protected Invocation getRequestInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Invocation invocation = new Invocation();

        try {
            if( req.getParameter("sessionId") != null )
                invocation.setSessionId( req.getParameter("sessionId") );

            String[] rq = getRequestInfo( req );
            invocation.setEntity(rq[ rq.length-2 ]);
            invocation.setMethod(rq[ rq.length-1 ]);

            String body = HttpServices.getJSONMessage(req);

            if( logger != null )
                logger.debug( "Received HTTP-Post body:" + body );

            invocation.setParameters( req.getMethod().equalsIgnoreCase("get")
                    ? HttpServices.getRequestParameters( req )
                    : JsonServices.<HashMap<String, Object>>parseJSON( body )
            );
        } catch (StreamLineException e) {
            throw new IOException( e );
        }

        return invocation;
    }

    @Override
    protected void sendResponse(HttpServletRequest req, HttpServletResponse resp, Object response) {
        try {
            if( logger != null )
                logger.debug( "Sending response message:" + response );

            if (response != null) {
                /*if (TypeServices.isSimpleType(response.getClass()))
                    HttpServices.sendResponseMessage(resp, response);
                else */
                HttpServices.sendJSONMessage(req, resp, response);
            }
        } catch (StreamLineException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doInnerPost(HttpServletRequest req, HttpServletResponse resp) throws StreamLineException, IOException {
        Invocation request = getRequestInfo(req, resp);

        Object res = call(request);

        if( res != null )
            sendResponse(req, resp, res);
    }

}
